#include"myStdio.h"
#include<unistd.h>
#include<stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>

MyFile* BuyMyFile(int fd, int flag)
{
    MyFile* fnode = (MyFile*)malloc(sizeof(MyFile));
    fnode->bufferlen = 0;
    fnode->fflush_method = LINE_FFLUSH;
    fnode->flag = flag;
    fnode->fileno = fd;

    memset(fnode->buffer, 0, sizeof(fnode->buffer));
    return fnode;
}

MyFile* Myfopen(const char* path,   const char* mode)
{
    int fd = -1;
    int flag = 0;
    if(strcmp(mode, "w")==0)
    {
        flag = O_CREAT | O_WRONLY | O_TRUNC;
        fd = open(path, flag, 0666);
    }
    else if(strcmp(mode, "r")==0)
    {
        flag = O_RDONLY;
        fd = open(path, flag);
    }
    else if(strcmp(mode, "a")==0)
    {
        flag = O_CREAT | O_APPEND | O_WRONLY;
        fd = open(path, flag, 0666);
    }
    else 
    {
        //其它打开方式
    }
    if(fd < 0)  return NULL;
    return BuyMyFile(fd,flag);
}
void Myclose(MyFile* filep)  
{
    if(filep->fileno < 0)   return; //打开文件错误
    Myfflush(filep);  //刷新缓冲区
    close(filep->fileno);   //关闭文件
    free(filep);    //释放资源
}
int Mywrite(MyFile* filep, void* str, int len)
{
    //拷贝数据
    memcpy(filep->buffer, str, len);
    //更新长度
    filep->bufferlen += len;
    //如果是换行并且刷新方法是行刷新就刷新
    if(filep->fflush_method==LINE_FFLUSH && filep->buffer[filep->bufferlen - 1 =='\n'])
        Myfflush(filep);
	
    return 0;
}
void Myfflush(MyFile* filep)
{
	if(filep->bufferlen < 0) 
    return;
	//将缓冲区内容写到系统里
	int n = write(filep->fileno,filep->buffer,filep->bufferlen);
	fsync(filep->fileno);
	filep->bufferlen=0;
}
